<template>
	<view class="su-attachment" :style="{width:compWidth}">
		<!-- 类型为file的 -->
		<view class="su-file" v-if="mode=='file'">
			<view class="su-item su-flex-row" v-for="(item, key) in list" :key="key">
				<view class="file-icon su-flex-row">
					<text class="before" v-if="item.uploadStatus==1||item.uploadStatus==-1"></text>
					<text class="iconfont success" v-if="item.uploadStatus==1">&#xe611;</text>
					<text class="iconfont error" v-if="item.uploadStatus==-1">&#xe6c9;</text>
					<image mode="aspectFill" :src="getIconUrl(item.docName,item.fileID)"></image>
				</view>
				<view class="file-content" @click="_preview(item)">
					<text class="name su-nowrap">{{item.docName}}</text>
					<!-- 状态集 -->
					<view class="status">
						<text class="progress" v-if="item.uploadStatus==0">上传中...({{item.process}}%)</text>
						<text class="progress error" v-if="item.uploadStatus==-1">上传失败，请稍后重试</text>
					</view>
					<text class="size" v-if="item.uploadStatus==1">{{byteString(item.size)}}</text>
				</view>
				<view class="file-operation" v-if="access=='edit'">
					<view class="delete" @click.stop="_deleteItem(item,key)">
						<text class="iconfont">&#xe66c;</text>
					</view>
				</view>
			</view>
			<view v-if="showAdd(list)" :class="['su-up-button','su-flex-row',(list && list.length>0)?'button-padding':'']" 
				  @click="_openSheet">
				<slot v-if="custom" name="button"></slot>
				<view v-else>
					<text class="iconfont icon font">&#xe64d;</text>
					<text class="font">添加附件</text>
				</view>
			</view>
		</view>
		<!-- 类型为image的 -->
		<view class="su-images" v-if="mode=='image'">
			<view class="image-item" v-for="(item,key) in list" :key="key" @click="_preview(item)">
				<text class="delete before" v-if="showDelete(item.uploadStatus)"></text>
				<text class="iconfont delete" v-if="showDelete(item.uploadStatus)"
					 @click.stop="_deleteItem(item,key)">&#xe637;</text>
				<view class="error su-pos-absolute" v-if="item.uploadStatus==-1">
					<text class="iconfont">&#xe6c9;</text>
					<text>上传失败</text>
				</view>
				<view class="progress su-pos-absolute">
					<progress :percent="item.process" :active-color="$mainColor"
					 :background-color="item.process == 100 || item.process == undefined ? $mainColor : '#ffffff'"
					 stroke-width="3" v-if="item.uploadStatus==0"/>
				</view>
				<image class="file-image" mode="aspectFill" :src="getFileUrl(item.docName,item.fileID)"></image>
			</view>
			<view class="image-item upload" v-if="showAdd(list)" @click="_openSheet">
				<text class="iconfont icon">&#xe613;</text>
			</view>
		</view>
		<!-- 弹出组件 -->
		<actionsheet tips="请选择" :show="showActionSheet"
					 :item-list="sheetData" @click="_sheetClick"
					 @cancel="showActionSheet=false"></actionsheet>
		<!-- #ifdef APP-PLUS -->
		<file-manager ref="fileManager"></file-manager>
		<!-- #endif -->
	</view>
</template>

<script>
	/**
	 * Attachment v1.0.4
	 * @author: Jie.
	 * @lastDate: 2020-05-30
	 */
	import fileManager from"./attachment/file-manager.vue";import actionsheet from"@/components/su-saui/su-actionsheet/actionsheet";export default{components:{fileManager:fileManager,actionsheet:actionsheet},props:{attachmentList:{type:[String,Array]},mode:{type:String,default:"file"},access:{type:String,default:"view"},fileType:{type:String,default:""},limit:{type:Number,default:null},fileKeyName:{type:String,default:"file"},canUploadFile:{type:Boolean,default:!0},custom:{type:Boolean,default:!1},compWidth:{type:String,default:"680rpx"},attId:{type:String,default:""},attPath:{type:String,default:""},directPicture:{type:Boolean,default:!1}},computed:{list(){var t=typeof this.attachmentList;if("string"==t){let t=[];try{t=JSON.parse(this.attachmentList)}catch(t){}for(var e in t)t[e].uploadStatus=1;return t}return"undefined"==t?[]:"object"==t&&this.attachmentList?this.attachmentList:[]},types(){if(this.fileType){var t=[];try{t=this.fileType.split(",")}catch(t){}return t}return[]},byteString:t=>(function(t){return uni.sutils.byteConvert(t)}),getIconUrl:(t,e)=>(function(t,e){return uni.doc.getIcon(t,e)}),getFileUrl:(t,e)=>(function(t,e){return uni.doc.getDownloadUrl(t,e)}),showDelete:t=>(function(t){return"edit"==this.access}),showAdd:t=>(function(){return"edit"==this.access&&!(null!=this.limit&&!isNaN(this.limit)&&this.list.length>=this.limit)})},data:()=>({showActionSheet:!1,sheetData:[],filesDelete:[],temparayUpload:[]}),methods:{_preview(t){var{docName:e,uploadStatus:i,fileID:s}=t;1==i&&uni.doc.filePreview(e,s)},_openSheet(){if(null!=this.limit&&!isNaN(this.limit)&&this.list.length>=this.limit)return uni.showToast({title:"已达到最大上传数量",icon:"none"});if("image"==this.mode&&1==this.directPicture&&1==this.canUploadFile)return this._chooseFile(0);var t=["拍照","从相册选择"];this.canUploadFile&&("android"==uni.getSystemInfoSync().platform&&"file"==this.mode&&t.push("从文件管理选择"),uni.sutils.isMp()&&"file"==this.mode&&t.push("从聊天文件选择"),this.sheetData=t,this.showActionSheet=!0)},_sheetClick(t){var{index:e}=t;this._chooseFile(1*e),this.showActionSheet=!1},async _chooseFile(t){var e="camera",i=[],s=null==this.limit||this.limit-this.list.length>9?9:9-this.limit;if(1==t&&(e="album"),0==t||1==t){if(void 0===(a=await uni.chooseImage({count:s,sizeType:["original","compressed"],sourceType:[e]}))[1])return;i=a[1].tempFilePaths}else if(2==t){if(uni.sutils.isApp())return this.$refs.fileManager._openFile(s,t=>{if(t.length>0){for(var e in t)t[e]="file:///"+t[e];i=t,this._uploadFile(i)}});if(uni.sutils.isMp()){var a=await new Promise((t,e)=>{wx.chooseMessageFile({count:s,type:"file",success(e){const i=e.tempFiles;t(i)}})});i=a.map((t,e)=>t.path),a.map((t,e)=>t.name)}}this._uploadFile(i)},async _uploadFile(t,e){for(let l in t){let o=t[l];if(void 0!==e&&void 0!==e[l])var i=e[l];else i=(i=o.split("/"))[i.length-1];let n=this.list.length;if(this.types.length>0){let t=uni.doc.getFileType(i);if(-1==this.types.indexOf(t))return uni.showToast({title:"只能上传"+this.fileType+"后缀的文件",icon:"none"})}this.list.push({docName:i,fileID:"",size:0,url:o,index:n,uploadTask:a,uploadStatus:0,process:0}),this.$forceUpdate();var s=uni.core.rendUrl(uni.doc.uploadUrl),a=await uni.uploadFile({url:s,filePath:o,name:this.fileKeyName,formData:{fileFileName:i},success:t=>{if(this.$emit("uploadSuccess",t),200==t.statusCode){var e=null;try{e=JSON.parse(t.data)}catch(t){return this.$set(this.list[n],"process",0),this.$set(this.list[n],"uploadStatus",-1),this.$forceUpdate()}var i=e.data;this.list[n]={...this.list[n],process:100,uploadStatus:1,docName:i.docName||"",fileID:i.fileID||"",size:1*i.size},this._uploadAfter(i.fileID)}else this.$set(this.list[n],"process",0),this.$set(this.list[n],"uploadStatus",-1);this.$forceUpdate()}});a.onProgressUpdate(t=>{this.list[n]?(this.$set(this.list[n],"process",t.progress),this.$forceUpdate()):a.abort()})}},_uploadAfter(t){var e="";t&&(this.temparayUpload.push(t),e=uni.doc.handleData(this.list),this.$emit("change",{type:"upload",data:e}),this.$emit("update:attachmentList",e))},_deleteItem(t,e){var i="";uni.showModal({title:"温馨提示",content:"确定要删除["+(t.docName||"")+"]吗?",confirmColor:this.$mainColor,success:s=>{s.confirm&&(this.list.splice(e,1),t.fileID&&this.filesDelete.push(t.fileID),i=uni.doc.handleData(this.list),this.$emit("change",{type:"delete",data:i}),this.$emit("update:attachmentList",i),this.$forceUpdate())}})},getResult(){return uni.doc.handleData(this.list)},getAttData(){return{attId:this.attId,attPath:this.attPath,filesDelete:this.filesDelete,temparayUpload:this.temparayUpload}},saveAfter(){this.filesDelete=[],this.temparayUpload=[]}}};
</script>

<style lang="scss">
	@import "./attachment/attachment.scss";
</style>
